package org.dromara.tearoom.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.tearoom.domain.bo.TerCouponBo;
import org.dromara.tearoom.domain.enums.CouponTakeTypeEnum;
import org.dromara.tearoom.domain.vo.TerCouponTemplateVo;
import org.dromara.tearoom.domain.vo.TerCouponVo;
import org.dromara.tearoom.domain.vo.TerOrderVo;
import org.dromara.tearoom.service.ITerCouponService;
import org.dromara.tearoom.service.ITerCouponTemplateService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 优惠劵
 * 前端访问路由地址为:/tearoom/coupon
 *
 * @author ckj
 * @date 2025-04-23
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/coupon")
public class TerCouponController extends BaseController {

    private final ITerCouponService terCouponService;
    private final ITerCouponTemplateService terCouponTemplateService;

    /**
     * 查询优惠劵列表
     */
    @SaCheckPermission("tearoom:coupon:list")
    @GetMapping("/list")
    public TableDataInfo<TerCouponVo> list(TerCouponBo bo, PageQuery pageQuery) {
        return terCouponService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出优惠劵列表
     */
    @SaCheckPermission("tearoom:coupon:export")
    @Log(title = "优惠劵", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TerCouponBo bo, HttpServletResponse response) {
        List<TerCouponVo> list = terCouponService.queryList(bo);
        ExcelUtil.exportExcel(list, "优惠劵", TerCouponVo.class, response);
    }

    /**
     * 获取优惠劵详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("tearoom:coupon:query")
    @GetMapping("/{id}")
    public R<TerCouponVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable("id") Long id) {
        return R.ok(terCouponService.queryById(id));
    }

    /**
     * 新增优惠劵
     */
    @SaCheckPermission("tearoom:coupon:add")
    @Log(title = "优惠劵", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TerCouponBo bo) {
        return toAjax(terCouponService.insertByBo(bo));
    }

    /**
     * 修改优惠劵
     */
    @SaCheckPermission("tearoom:coupon:edit")
    @Log(title = "优惠劵", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TerCouponBo bo) {
        return toAjax(terCouponService.updateByBo(bo));
    }

    /**
     * 删除优惠劵
     *
     * @param ids 主键串
     */
    @SaCheckPermission("tearoom:coupon:remove")
    @Log(title = "优惠劵", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable("ids") Long[] ids) {
        return toAjax(terCouponService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 发送优惠劵
     * @param bo
     * @return
     */
    @PostMapping("/send")
    @Log(title = "发送优惠劵", businessType = BusinessType.INSERT)
    @SaCheckPermission("tearoom:coupon:send")
    public R<Void> sendCoupon(@Valid @RequestBody TerCouponBo bo) {
        terCouponService.takeCouponByAdmin(bo.getTemplateId(), bo.getUserIds(), bo.getRemark());
        return R.ok();
    }

    /**
     * 我的优惠劵列表
     * @param bo
     * @param pageQuery
     * @return
     */
    @GetMapping("/appPage")
    public TableDataInfo<TerCouponVo> getCouponPage(TerCouponBo bo, PageQuery pageQuery) {
        bo.setUserId(LoginHelper.getAppLoginUser().getId());
        return terCouponService.queryPageList(bo, pageQuery);
    }

    /**
     * 计算价格
     * @param bo
     * @return
     */
    @PostMapping("/calculatePrice")
    public R<TerOrderVo> calculatePrice(@Valid @RequestBody TerCouponBo bo) {
        return R.ok(terCouponService.calculatePrice(bo.getId(),LoginHelper.getAppLoginUser().getId(),bo.getUseOrderId()));
    }

    /**
     * 领取优惠券
     * @param reqVO
     * @return
     */
    @PostMapping("/take")
    public R<Boolean> takeCoupon(@Valid @RequestBody TerCouponBo reqVO) {
        // 1. 领取优惠劵
        Long userId = LoginHelper.getAppLoginUser().getId();
        terCouponService.takeCoupon(reqVO.getTemplateId(), CollUtil.newHashSet(userId), CouponTakeTypeEnum.USER,reqVO.getRemark(),null);
        // 2. 检查是否可以继续领取
        TerCouponTemplateVo couponTemplate = terCouponTemplateService.queryById(reqVO.getTemplateId());
        if(ObjectUtil.isEmpty(couponTemplate)){
            throw new ServiceException("优惠券不存在!");
        }
        boolean canTakeAgain = true;
        if (couponTemplate.getTakeLimitCount() != null && couponTemplate.getTakeLimitCount() > 0) {
            Integer takeCount = terCouponService.getTakeCount(reqVO.getTemplateId(), userId);
            canTakeAgain = takeCount < couponTemplate.getTakeLimitCount();
        }
        return R.ok(canTakeAgain);
    }
}
